package com.yuanmei.charts;


import android.util.Log;

import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

/**
 * http://stackoverflow.com/questions/28521004/mpandroidchart-have-one-graph-mirror-the-zoom-swipes-on-a-sister-graph
 */
public class CoupleValueSelectedListener implements OnChartValueSelectedListener {

    private static final String TAG = "SyncValueSelected";

    private TaCombinedChart mSource;
    private TaCombinedChart mTarget;
    private OnDataIndexChangedListener mOnDataIndexChangedListener;

    public interface OnDataIndexChangedListener {
        void onSelectedDataIndexChanged(int dataIndex);
    }

    public CoupleValueSelectedListener(TaCombinedChart source,
                                       TaCombinedChart target,
                                       OnDataIndexChangedListener listener) {
        this.mSource = source;
        this.mTarget = target;
        this.mOnDataIndexChangedListener = listener;
    }

    @Override
    public void onValueSelected(Entry e, Highlight sHighlight) {
        float targetYPx = sHighlight.getYPx() - mSource.getHeight();
        Highlight forkHiglight;
        Highlight oldHiglight = mTarget.getHighlightByTouchPoint(sHighlight.getXPx(), targetYPx);
        if (null == oldHiglight) {
            forkHiglight = new Highlight(
                    sHighlight.getX(), sHighlight.getY(),
                    sHighlight.getXPx(), 0, 0,
                    sHighlight.getDataSetIndex(), sHighlight.getAxis());
            forkHiglight.setDataIndex(0);
        } else {
            forkHiglight = new Highlight(
                    sHighlight.getX(), sHighlight.getY(),
                    sHighlight.getXPx(), targetYPx, sHighlight.getDataIndex(),
                    sHighlight.getDataSetIndex(), sHighlight.getAxis());
            forkHiglight.setDataIndex(oldHiglight.getDataIndex());
        }

        mTarget.highlightValues(new Highlight[]{forkHiglight});
        Log.d(TAG, "onValueSelected X=" + sHighlight.getX());
        if (mOnDataIndexChangedListener != null) {
            mOnDataIndexChangedListener.onSelectedDataIndexChanged((int) sHighlight.getX());
        }
    }

    @Override
    public void onNothingSelected() {
        mTarget.highlightValue(null);
    }
}